// 账户体系模块处理函数

const utils = require("../common/utils")
// 密码加密模块
const bcrypt = require('bcryptjs')
// 引入邮箱服务
const transporter = require('../config/smtp.js')
const server = require("../server/account")

// 注册
exports.register = async (req, res) => {
  const {
    user_name,
    email,
    password,
    qrCode
  } = req.body;
  // 判断验证码
  try{
    let qrcode = await server.getQrCode(email)
    if (qrcode) {
      if (qrCode == qrcode) {
        let result = await server.register(user_name, email, password)       
        if (result == '邮箱已被注册') {
          return res.cc(result)
        } else {
          return res.cc(result, 200)
        }        
      } else {
        return res.cc("验证码错误，请重新输入")
      }
    } else {
      return res.cc("验证码无效，请重新获取")
    }
  } catch(e){
    return res.cc("服务器异常", 500)
  }
}

// 登录
exports.login = (req, res) => {
  let { email, password } = req.body
  if (!email || !password) return res.cc('邮箱或密码不合法')
  server.login(email, password).then(result => {
    return res.send({
      code: 200,
      message: '登录成功',
      data: {
        token: 'Bearer ' + result
      }
    })
  }).catch(err => {
    return res.cc(err, 400)
  }) 
}

// 获取验证码
exports.qrCode = async (req, res) => {
  let email = req.body.email;
  if (!email) return res.cc('请输入邮箱')
  let qrcode = utils.randomNumber()
  try {
    let result = await server.setQrCode(email, qrcode);
    if (result) {
      transporter.sendMail({
        subject: '验证码',
        from: '1811082435@qq.com',
        to: email,
        text: `你好，你的验证码是：${qrcode}，请勿告知他人，以防个人信息泄露。`
      }, (err, msg) => {
        if (err) return res.cc(err)
        return res.cc("验证码已发送", 200)
      })
    }
  } catch (e) {
    return res.cc("服务器异常", 500)
  }
}
